<template>
  <div class="app-container">
    <div class="filter-container">
      <div class="search-container">
        <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
          查询
        </el-button>
        <el-button class="filter-item" style="margin-left: 10px;" type="success" icon="el-icon-edit" @click="handleCreate">
          新增
        </el-button>
      </div>
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNo" :layout="'total, sizes, prev, pager, next, jumper'" :limit.sync="listQuery.pageSize" @pagination="getOrganizations" />
    </div>

    <el-table
      :key="tableKey"
      v-loading="organizationLoading"
      :data="organizations"
      border
      fit
      row-key="id"
      default-expand-all
      style="width: 100%;"
    >
      <el-table-column label="名称">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="描述" align="center">
        <template slot-scope="{row}">
          <span>{{ row.intro || '暂无' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="得分" align="center">
        <template slot-scope="{row}">
          <span>{{ row.score }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false" :width="'500px'">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:40px;">
        <el-form-item label="名称" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="简介">
          <el-input v-model="temp.intro" />
        </el-form-item>
        <el-form-item label="经理" prop="head">
          <el-select v-model="temp.head" class="filter-item" placeholder="请选择" @change="$forceUpdate()">
            <el-option v-for="item in usersOptions" :key="item.id" :label="item.nickname" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="归属" prop="parent_id">
          <el-select v-model="temp.parent_id" class="filter-item" placeholder="请选择">
            <el-option v-for="item in orign_organizations" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { parseTime, data2Tree } from '@/utils'
import Pagination from '@/components/Pagination'
import * as UserApi from '@/api/user'
import * as OrganizationApi from '@/api/organization'

export default {
  name: 'Organization',
  components: { Pagination },
  filters: {
    parseTimeFilter(time) {
      return parseTime(time)
    }
  },
  data() {
    return {
      tableKey: 0,
      total: 0,
      organizationLoading: true,
      listQuery: {
        pageNo: 1,
        pageSize: 99
      },
      organizations: [],
      usersOptions: [],
      orign_organizations: [],
      temp: {
        name: '',
        intro: '',
        head: '',
        parent_id: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '详情编辑',
        create: '新增'
      },
      rules: {
        name: [{ required: true, message: '必须填写名称', trigger: 'blur' }],
        head: [{ required: true, message: '必须填写经理', trigger: 'blur' }],
        parent_id: [{ required: true, message: '必须填写归属部门', trigger: 'blur' }]
      }
    }
  },
  computed: {
    ...mapGetters([
      'userInfo',
      'cur_organization_id'
    ])
  },
  created() {
    this.getOrganizations()
    this.getUsers()
  },
  methods: {
    async getOrganizations(pageQuery) {
      if (pageQuery) {
        this.listQuery = Object.assign(this.listQuery, pageQuery)
      }
      this.organizations = []
      this.orign_organizations = []
      this.organizationLoading = true
      const { data } = await OrganizationApi.getOrganizaitons(this.listQuery)
      if (data.total) {
        this.orign_organizations = data.items
        this.organizations = data2Tree(data.items)
        this.total = data.total
      }
      this.organizationLoading = false
    },
    async getUsers() {
      this.usersOptions = []
      const { data } = await UserApi.getUserList({ pageNo: 1, pageSize: 999 })
      if (data && data.total) {
        this.usersOptions = data.items
      }
    },
    handleFilter() {
      this.listQuery.pageNo = 1
      this.getOrganizations()
    },
    resetTemp() {
      this.temp = {
        name: '',
        intro: '',
        parent_id: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(async(valid) => {
        if (valid) {
          const { data } = await OrganizationApi.createOrganization(this.temp)
          if (data) {
            await this.getOrganizations()
            await this.$notify({
              title: 'Success',
              message: '新增成功',
              type: 'success',
              duration: 2000
            })
            this.dialogFormVisible = false
          }
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(async(valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          const { data } = await OrganizationApi.updateOrganization(tempData)
          if (data) {
            this.dialogFormVisible = false
            await this.getOrganizations()
            await this.$notify({
              title: 'Success',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          }
        }
      })
    },
    handleDelete(row, index) {
      this.$confirm('此操作删除该项, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const { data } = await OrganizationApi.deleteOrganization(row.id)
        if (data) {
          await this.getOrganizations()
          await this.$notify({
            title: 'Success',
            message: '删除成功！',
            type: 'success',
            duration: 2000
          })
        }
      }).catch(() => {
        this.$notify({
          title: 'Fail',
          message: '已取消删除',
          type: 'error',
          duration: 2000
        })
      })
    }
  }
}
</script>

<style scoped>
.filter-container {
  display: flex;
  justify-content: space-between;
}
.pagination {
  display: flex;
  justify-content: center;
  margin-top: 1rem;
}
</style>
